<?php

namespace addons\facrm\controller\open;


use addons\facrm\library\OpenApi;
use app\admin\model\facrm\Fields;
use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;


/**
 * 线索管理
 * @ApiInternal
 * @icon fa fa-circle-o
 */
class Clues extends OpenApi
{

    protected $model = null;
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->request->filter(['strip_tags']);
    }

    /**
     * 添加线索
     * @return mixed
     */
    public function add()
    {
        $params = $this->request->post();
        if ($params) {

            if (!$this->setting) $this->error(__('配置有误'));
            $values = $this->setting['values'];

            $owner_user_ids = [];
            //如果选择了组、没有选择成员 自动分配客户
            if (!$values['owner_user_id'] && $values['group_id']) {

                $groupList = collection(\app\admin\model\AuthGroup::cache('FacrmAuthGroup')->select())->toArray();

                Tree::instance()->init($groupList);
                $groupIds = Tree::instance()->getChildrenIds($values['group_id'], true);
                $authGroupList = \app\admin\model\AuthGroupAccess::
                field('uid,group_id')
                    ->where('group_id', 'in', $groupIds)
                    ->select();
                foreach ($authGroupList as $k => $v) {
                    if (in_array($v['uid'], $owner_user_ids)) continue;
                    $owner_user_ids[] = $v['uid'];
                }

            } else {
                $owner_user_ids = explode(',', $values['owner_user_id']);
            }
            //添加
            $owner_user_id = $owner_user_ids ? $owner_user_ids[mt_rand(0, count($owner_user_ids) - 1)] : 0;

            $add_data =array_merge($params,
                [
                    'telephone' => '',
                    'source' => $values['source'],
                    'create_user_id' => 0,
                    'owner_user_id' => $owner_user_id,
                    'next_time' =>time(),//提醒跟进
                    'follow_time' => time(),
                    'collect_time' => time(),
                    'remark' =>isset($params['remark'])? $params['remark'].$this->setting['describe']:$this->setting['describe'],
                ]) ;

            //校验数据
            $cresult = Fields::validateByForm('clues', $add_data);
            if (!$cresult['status']) {
                $this->error(__($cresult['msg']));
            }


            $result = false;
            Db::startTrans();
            try {
                $model = new \app\admin\model\facrm\Clues();
                $result = $model->add($params);
                Db::commit();
            } catch (ValidateException $e) {

                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success('',$result);
            } else {
                $this->error(__('No rows were inserted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', ''));
    }


}
